package com.tutu.common;

import com.tutu.utils.BaseUtil;
import com.tutu.utils.JsonUtil;
import org.springframework.data.domain.Page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tuyh on 14-10-21.
 */
public class DataTableFactory {

    public static Map<String, Object> fitting(Integer draw, Object obj) {
        Map<String, Object> map = JsonUtil.json2Map(obj);

        if (!map.containsKey("code")) {
            map.put("data", map.containsKey("content") ? map.get("content") : new ArrayList<>());
            map.put("draw", draw);
            map.put("iTotalRecords", map.get("total"));
            map.put("iTotalDisplayRecords", map.get("total"));

            map.remove("content");
            map.remove("pageable");
        } else {
            if (!map.get("code").equals(0)) {
                return BaseUtil.defaultErrorInfo(map.get("msg") + "");
            } else {
                return JsonUtil.json2Map(map.get("data"));
            }
        }

        return map;
    }

    public static Map<String, Object> fitting(Integer draw, Page<?> page) {
        List<?> list = page.getContent();
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        map.put("draw", draw);
        map.put("iTotalRecords", page.getTotalElements());
        map.put("iTotalDisplayRecords", page.getTotalElements());
        return map;
    }
}